package com.ruicar.afs.cloud.manage.creditchange.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.aspect.DataAccess;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.CustInfoChangeTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ProcessStatusEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.image.condition.OcrDiscernCondition;
import com.ruicar.afs.cloud.manage.common.entity.ComAttachementFile;
import com.ruicar.afs.cloud.manage.common.entity.ManageCustInfoChange;
import com.ruicar.afs.cloud.manage.common.service.ComAttachementFileService;
import com.ruicar.afs.cloud.manage.common.service.ContractOCRInterService;
import com.ruicar.afs.cloud.manage.common.service.ManageCustInfoChangeService;
import com.ruicar.afs.cloud.manage.common.vo.IdCardBackOcrDiscernVo;
import com.ruicar.afs.cloud.manage.common.vo.IdCardFrontOcrDiscernVo;
import com.ruicar.afs.cloud.manage.creditchange.condition.CustInfoChangeCondition;
import com.ruicar.afs.cloud.manage.creditchange.enums.BankTemplateIdEnum;
import com.ruicar.afs.cloud.manage.creditchange.vo.CustInfoManageVO;
import com.ruicar.afs.cloud.manage.workflow.processor.ApproveTaskProcessor;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author chuke
 * @create 2020/7/4 14:01
 */
@Slf4j
@RestController
@RequestMapping("/custInfoChange")
@AllArgsConstructor
public class CustInfoChangeController {
    private final ManageCustInfoChangeService manageCustInfoChangeService;
    private final ApproveTaskProcessor approveTaskProcessor;
    private final ContractOCRInterService contractOCRInterService;
    private final ComAttachementFileService comAttachementFileService;


    @DataAccess(tables = {"manage_cust_info_change"}, key = "condition.channelId")
    @ApiOperation(value = "身份信息申请或暂存过的案件列表")
    @PostMapping("/getManageCustInfoChangeList")
    public IResponse getManageCustInfoChangeContractNo(@RequestBody CustInfoChangeCondition condition) {

        condition.setProcessPerson(SecurityUtils.getUser().getUserRealName());
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage list = manageCustInfoChangeService.getManageCustInfoChangeList(page, condition);
        list.setRecords(approveTaskProcessor.handle(list.getRecords()));
        return new IResponse().setData(list);
    }


    @ApiOperation(value = "保存身份变更信息")
    @PostMapping("/changeContractCustInfo")
    public IResponse contractCustInfoChange(@RequestBody CustInfoManageVO custInfoManageVO) {
        //  TODO CK  1、担保人可能会有多个，后续添加
        ManageCustInfoChange custInfoChange = manageCustInfoChangeService.saveCustInfoRecord(custInfoManageVO);
        //保存后返填数据到页面上
        return new IResponse<>().setData(custInfoChange);
    }


    @ApiOperation(value = "查询身份变更详细信息")
    @PostMapping("/findCustInfoDetial")
    public IResponse findCustInfoDetial(@RequestBody ManageCustInfoChange custInfoChange) {
        ManageCustInfoChange change = manageCustInfoChangeService.getOne(Wrappers.<ManageCustInfoChange>lambdaQuery()
                .eq(ManageCustInfoChange::getCaseNo, custInfoChange.getCaseNo()));
        if (change == null || change.getCaseNo() == null) {
            ManageCustInfoChange custInfo = new ManageCustInfoChange();
            return new IResponse().setData(custInfo);
        }
        return new IResponse<>().setData(change);
    }


    @ApiOperation(value = "删除身份变更记录")
    @PostMapping("/delCustInfo")
    public IResponse delCustInfo(@RequestBody ManageCustInfoChange change) {
        manageCustInfoChangeService.remove(Wrappers.<ManageCustInfoChange>lambdaQuery()
                .eq(ManageCustInfoChange::getCaseNo, change.getCaseNo()));
        return new IResponse().success("删除成功");
    }


    @PostMapping("/submitCustInfoManage")
    @ApiOperation(value = "提交身份变更信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse submitCustInfoManage(@RequestBody CustInfoManageVO manageVO) {
        manageCustInfoChangeService.submitCustInfoRecord(manageVO);
        return new IResponse<Boolean>().setData(true).setMsg("流程提交成功！");
    }


    @PostMapping("/saveProposalApplicationInfo")
    @ApiOperation(value = "流程审批操作")
    @Transactional(rollbackFor = Exception.class)
    public IResponse saveProposalApplicationInfo(@RequestBody CustInfoManageVO manageCancelRecord) {
        manageCustInfoChangeService.saveProposalApplicationInfo(manageCancelRecord);
        return new IResponse<Boolean>().setData(true).setMsg("流程审批成功！");
    }

    @PostMapping("/getOCRCustInfo")
    @ApiOperation(value = "OCR识别填充数据")
    public IResponse getOCRInfo(@RequestBody CustInfoManageVO manageVO) {
        ManageCustInfoChange custInfoData = manageCustInfoChangeService.getOne(Wrappers.<ManageCustInfoChange>lambdaQuery()
                .eq(ManageCustInfoChange::getCaseNo, manageVO.getCaseNo()));
        if (custInfoData != null && custInfoData.getProcessStatus() != ProcessStatusEnum.draft) {
            return new IResponse().setData(null);
        }
        List<ComAttachementFile> idCardFront = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                .eq(ComAttachementFile::getBusiNo, manageVO.getCaseNo())
                .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.CustInfoIdCardForontCode.getDesc())
                .orderByDesc(ComAttachementFile::getCreateTime));
        List<ComAttachementFile> idCardBack = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                .eq(ComAttachementFile::getBusiNo, manageVO.getCaseNo())
                .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.CustInfoIdCardBackCode.getDesc())
                .orderByDesc(ComAttachementFile::getCreateTime));
        ManageCustInfoChange custInfoChange = new ManageCustInfoChange();
        if (idCardFront.size() != 0) {//身份证正面
            OcrDiscernCondition idCardFrontCondition = new OcrDiscernCondition();
            idCardFrontCondition.setCaseCode(idCardFront.get(0).getBusiNo()); //业务编号
            idCardFrontCondition.setInletEnd("PC");//进件端
            idCardFrontCondition.setSysCode("ICOS");//系统标识
            idCardFrontCondition.setFileCode("idCardFront");//文件类型
            idCardFrontCondition.setFileMd5(idCardFront.get(0).getFileId());
            IdCardFrontOcrDiscernVo idCardFrontOcrDiscern = contractOCRInterService.getIdCardFrontOcrDiscern(idCardFrontCondition);
            if (idCardFrontOcrDiscern != null) {
                custInfoChange.setNewName(StringUtils.isNotEmpty(idCardFrontOcrDiscern.getName()) ? idCardFrontOcrDiscern.getName() : null);
                custInfoChange.setNewCertNo(StringUtils.isNotEmpty(idCardFrontOcrDiscern.getNumber()) ? idCardFrontOcrDiscern.getNumber() : null);
            }
        }
        if (idCardBack.size() != 0) {//身份证反面
            OcrDiscernCondition idCardBackCondition = new OcrDiscernCondition();
            idCardBackCondition.setCaseCode(StringUtils.isNotEmpty(custInfoChange.getCaseNo()) ? custInfoChange.getCaseNo() : "idCardBack"); //业务编号
            idCardBackCondition.setInletEnd("PC");//进件端
            idCardBackCondition.setSysCode("ICOS");//系统标识
            idCardBackCondition.setFileCode("idCardBack");//文件类型
            idCardBackCondition.setFileMd5(idCardFront.get(0).getFileId());
            IdCardBackOcrDiscernVo idCardBackOcrDiscern = contractOCRInterService.getIdCardBackOcrDiscern(idCardBackCondition);
            if (idCardBackOcrDiscern != null) {
                custInfoChange.setNewCertStartDate(EmptyUtils.isNotEmpty(idCardBackOcrDiscern.getLssueDate()) ? idCardBackOcrDiscern.getLssueDate() : null);//签发日期
                custInfoChange.setNewCertEndDate(EmptyUtils.isNotEmpty(idCardBackOcrDiscern.getValidUntil()) ? idCardBackOcrDiscern.getValidUntil() : null);//截至日期
            }
        }
        if ((idCardBack.size() == 0 && idCardFront.size() == 0)
                || manageVO.getCaseNo() == null
                || manageVO.getChangeSubject().equals(CustInfoChangeTypeEnum.other)
                || manageVO.getChangeSubject().equals(CustInfoChangeTypeEnum.expirationDate)){
            return new IResponse().setData(null);
        }
        //根据变更类型编辑识别出来的数据
        if (manageVO.getChangeSubject().equals(CustInfoChangeTypeEnum.name) ){
            custInfoChange.setNewName(null);
        }
        return new IResponse().setData(custInfoChange);
    }

}
